package servlet;

import dao.PostDao;
import dao.PostDaoImpl;
import io.jsonwebtoken.Claims;
import org.json.JSONObject;
import pojo.Post;
import redis.RedisDao;
import redis.RedisDaoImpl;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;

import static util.JwtUtil.parseJWT;
import static util.JwtUtil.validateJWT;
import static util.REUtile.getRedis;

public class CreatePostServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
//        验证token
        String token=req.getParameter("token");
        JSONObject result=new JSONObject(req.getParameter("result"));
        JSONObject obj=new JSONObject();
//        如果通过
        int postid;
        if(validateJWT(token)){
            Claims claims=parseJWT(token);
            int account=Integer.parseInt(claims.getId());
            Post post=new Post();
            post.setPostContent(result.getString("content"));
            post.setPostAccount(result.getInt("account"));
            post.setPostType(result.getInt("type"));
            post.setPostTitle("手机插入的");
            post.setProTimer(new Timestamp(System.currentTimeMillis()));
            post.setStarNum(0);
            PostDao dao=new PostDaoImpl();
            postid = dao.insertPost(post);
            System.out.println(postid);
            post.setPostId(postid);
            RedisDao redisDao=new RedisDaoImpl();
            if(redisDao.addPost(post)&&redisDao.addUserPost(postid,account)){
                Jedis jedis=getRedis();
                jedis.select(0);
                jedis.lpush("order",String.valueOf(postid));
            }
            obj.put("result",1);
            obj.put("postId",postid);
        }else{
            System.out.println("令牌有误，非法入侵");
            obj.put("result",0);
        }
        resp.setContentType("text/json; charset=utf-8");
        PrintWriter out=resp.getWriter();
        out.print(obj);
    }
}
